/**
 * Created by WUWE4 on 8/3/2017.
 */
$(document).ready(function () {
	function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }
    var mId = getUrlParam("mId");
     $.ajax({
         url: "DishListServlet?mId=" + mId,
         method: "GET",
         success: function (data) {
        	 console.log(data);
        	 data.dishes.forEach(function (item, index, arr) {
        	        var dishes = $("#dishes");
        	        var imageUrl = "ImageLoader?path=" + item.dImageUrl;
        	        var link = "dishes.html?mId=" + item.mId;
        	        dishes.append(
        	            "<div class='col-md-4'>" +
        	                "<div class='thumbnail'>" +
        	                    "<img src='" + imageUrl + "'>" +
        	                    "<div class='caption'>" +
        	                        "<h3>" + item.dName + "</h3>" +
        	                        "<p>Price: " + item.dPrice + "</p>" +
//        	                        "<a href='#' class='btn btn-primary' role='button'>加入购物车</a>"+
        	                        "<a href='#' class='btn btn-primary addcar' mid='"+item.mId+"' did='"+item.dId+"' role='button'>加入购物车</a>"+
        	                    "</div>" +
        	                "</div> " +
        	            "</div>");
        	    });

        	    data.dishtype.forEach(function (item, index, arr) {
        	        var dishtype = $("#dishtype");
        	        var liId = "li" + item.pId;
        	        dishtype.append(
        	            "<li id='"+liId+"'><a href='#'>"+ item.pname + "</a></li>"
        	        );
        	        $("#"+liId).on("click", function (event) {
        	            $.ajax({
        	            	url: "DishListServlet?mId=" + mId + "&type=" + item.pId,
        	                method:"GET",
        	                success:function (data) {
        	                    //根据菜种类找菜品
        	                	var dishes = $("#dishes");
        	                	dishes.html("");
        	                	data.dishes.forEach(function (item, index, arr) {
        	            	        
        	            	        var imageUrl = "ImageLoader?path=" + item.dImageUrl;
        	            	        var link = "dishes.html?mId=" + item.mId;
        	            	        dishes.append(
        	            	            "<div class='col-md-4'>" +
        	            	                "<div class='thumbnail'>" +
        	            	                    "<img src='" + imageUrl + "'>" +
        	            	                    "<div class='caption'>" +
        	            	                        "<h3>" + item.dName + "</h3>" +
        	            	                        "<p>Price: " + item.dPrice + "</p>" +
        	            	                        "<a href='#' class='btn btn-primary' mid='"+item.mId+"' did='"+item.dId+"' role='button'>加入购物车</a>"+
        	            	                    "</div>" +
        	            	                "</div> " +
        	            	            "</div>");
        	            	    });
        	                }
        	            });
        	        });
        	    });

        	    $("#title").html(data.merchant.mName + " Dishes");
        	    
        	    if(data.loginToken) {
                	var customer = data.loginToken;
                	$("#header").append(
                		"<label style='font-size: x-large'>"+ 
                		customer.cname + 
                   		"</label>&nbsp"
                	);
                	$("#header").append(
                    	"<a style='font-size: x-large' href='LogoutServlet'>"+ 
                    	"Logout" + 
                       	"</a>"
                    );
                } else {
                	$("#header").append(
                    	"<a style='font-size: x-large' data-toggle='modal' data-target='#LoginForm'>"+ 
                    	"Login" + 
                       	"</a>&nbsp"
                    );
                	$("#header").append(
                        "<a style='font-size: x-large' data-toggle='modal' data-target='#RegistForm'>"+ 
                        "Regist" + 
                        "</a>"
                    );
                }
        	    var mmid=data.merchant.mId;
        	    
                $(function () {
                	if(JSON.parse(localStorage.getItem("list"))!=undefined){
                	operateDom();}
                    var offset = $("#end").offset();
//                    var list=localStorage.getItem("list");
//                    if(list === null || list === undefined) {
//                    	list = [];
//                    }

                    console.log(mmid);
                    function cart() {
                        this.mid={};
                        this.cars=[];
                    }
                    var cartList=new cart();
                    function sendRequest(data) {
                        $.ajax({
                            url:"CarServlet",
                            method:"POST",
                            data:data,
                            success:function (data) {
//                            	console.log(data);
//                                var jsonList=data.cars;
//                                cartList.cars=jsonList;
// 
//                                console.log(cartList.carts);
//                                localStorage.setItem("carts",JSON.stringify(list));
//                                var d = localStorage.getItem("carts");  
//                                console.log(foo);
//                                jsonList.forEach(function (item,index,array) {
//                                    var dId=item.dId;
//                                    var dish=item.dish;
//                                    var num=item.num;
//                                    
//
//                                })
                            	
                            	var list=JSON.parse(localStorage.getItem("list"));
                                if(list === null || list === undefined) {
                                	list = [];
                                }
                            	var flag=true;
                            	cartList.cars=data.cars;
                            	list.forEach(function(item,index,array){
                            		if(item.mid==cartList.mid)
                            			{
                            				flag=false;
                            				item.cars=cartList.cars;
                            			}
                            	});
                            	if(flag)
                            		{
                            			list.push(cartList);
                            		}
                            	localStorage.setItem("list",JSON.stringify(list));
                            	operateDom();
                            }
                        });
                    }

                    function operateDom(){
                    	var clist=JSON.parse(localStorage.getItem("list"));
                    	var group=$(".panel-group");
                    	group.html("");
                    	console.log(group);
                    	clist.forEach(function(item,index,array){
                    		
                    		console.log(item.mid);
                    		if(item.cars.length!=0){
                    		group.append(" <div class='panel panel-default' id='"+item.mid+"-panel'>"+
                                    "<div class='panel-heading' role='tab' id='headingtr'>"+
                                        "<h4 class='panel-title'>"+
                                            "<a class='collapsed' role='button' data-toggle='collapse'"+
                                               "data-parent='#accordion' href='#"+item.mid+"' aria-expanded='false'"+
                                               "aria-controls='"+item.mid+"'>"+
                                               item.mid+
                                            "</a>"+
                                        "</h4>"+
                                    "</div>"+
                                    "</div>");
                    		panel=$("#"+item.mid+"-panel");
                    		panel.append("<div id='"+item.mid+"' class='panel-collapse collapse' role='tabpanel'"+
                                    "aria-labelledby='"+item.mid+"-panel'>"+
                                   "<div class='panel-body'>"+
                                   "<div class='tbar-cart-list' id='"+item.mid+"-list'>"+
                                   "</div>"+
                                   "</div>"+
                               "</div>");
               			panel_body=$("#"+item.mid+"-list");
                    		var dlist=item.cars;
                    		dlist.forEach(function(ditem,index,array){
                    			var dish=ditem.dish;
                    			var imageUrl = "ImageLoader?path=" + dish.dImageURL;
                    			panel_body.append(
                                        "<div class='tbar-cart-item' id='"+ditem.dId+"-item'>"+
                                        "<div class='jtc-item-goods'>"+
                                            "<span class='p-img'><a href='#'>" +
                                            		"<img src='"+imageUrl+"' height='50' width='50'/></a></span>"+
                                            "<div class='p-name'>"+
                                                "<a href='#'>"+dish.dName+"</a>"+
                                            "</div>"+
                                            "<div class='p-price'><strong>¥"+dish.dPrice+"</strong></div>"+
                                            "<div class='p-num'>"+
                                               "<input class='min' name='' mid='"+dish.mId+"' did='"+ditem.dId+"' type='button' value='-' />"+
                                                "<input class='num' name='' type='text' mid='"+dish.mId+"' did='"+ditem.dId+"' value='"+ditem.num+"' />"+
                                                "<input class='add' name='' type='button' mid='"+dish.mId+"' did='"+ditem.dId+"' value='+' />"+ 
                                           "</div>"+
                                            "<a href='#none' class='p-del J-del' mid='"+dish.mId+"' did='"+ditem.dId+"'>删除</a>"+
                                   "</div>"+
                    "</div>");
                    			
                    			

                    			$('#'+ditem.dId+"-item").hover(function (){ $('#'+ditem.dId+"-item").find('.p-del').show(); },function(){ $('#'+ditem.dId+"-item").find('.p-del').hide(); });
                    			$('#'+ditem.dId+"-item").find(".p-del").click(function () {
                                    var del=$(this);
                                    
                                    var mid=del.attr("mid");
                                    cartList.mid=mid;
                                    var did=del.attr("did");
                                    var num="0";
                                    var action="delete";
                                    var data={mId:mid,dId:did,num:num,action:action};
                                    sendRequest(data);
                                });

                        		$('#'+ditem.dId+"-item").find(".min").click(function () {
                                	
                                    var min=$(this);
                                    var mid=min.attr("mid");
                                    cartList.mid=mid;
                                    var did=min.attr("did");
                                    var num="1";
                                    var action="reduce";
                                    var data={mId:mid,dId:did,num:num,action:action};
                                    sendRequest(data);
                                });

                        		$('#'+ditem.dId+"-item").find(".add").click(function () {
                                	
                                    var add=$(this);
                                   
                                    var mid=add.attr("mid");
                                    cartList.mid=mid;
                                    var did=add.attr("did");
                                    var num="1";
                                    var action="add";
                                    var data={mId:mid,dId:did,num:num,action:action};
                                    sendRequest(data);
                                });
                    		});
                    		
                    		
//                            $(".num").click(function () {
//                                var num=$(this);
//                                var mid=num.attr("mid");
//                                var did=num.attr("did");
//                                var num=num.val();
//                                var action="update";
//                                var data={mId:mid,dId:did,num:num,action:action};
//                                sendRequest(data);
//                            });

                    	}
                    	})
                    	
                    }
                    
                    

                    $(".addcar").click(function (event) {
                        var addcar = $(this);
                        var img = addcar.parent().parent().find('img').attr('src');
                        var flyer = $('<img class="u-flyer" src="' + img + '">');
                        var mid=addcar.attr("mid");
                        var did=addcar.attr("did");
                        var num="1";
                        var method="add";
                        cartList.mid=mid;
                        var data={mId:mid,dId:did,num:num,action:method};
                        sendRequest(data);
                        flyer.fly({
                            start: {
                                left: event.pageX, //开始位置（必填）#fly元素会被设置成position: fixed
                                top: event.pageY //开始位置（必填）
                            },
                            end: {
                                left: offset.left + 10, //结束位置（必填）
                                top: offset.top + 10, //结束位置（必填）
                                width: 0, //结束时宽度
                                height: 0 //结束时高度
                            },
                            onEnd: function () { //结束回调
                                $("#msg").show().animate({width: '150px', height: '150px'}, 200).fadeOut(1000); //提示信息

                                this.destory(); //移除dom
                            }
                        });
                    });
                });
         }
     });

    $("#loginbtn").on("click", function (event) {
        var username = $("#username1").val();
        var password = $("#password1").val();
        var logindata = {
            username: username,
            password: password
        };
        $.ajax({
            url:"LoginServlet",
            method: "POST",
            data: logindata,
            success: function (data) {
                //登录成功
            	window.location.href=window.location.href;
            }
        });
    });

    $("#regbtn").on("click",function (event) {
        var username = $("#username2").val();
        var password = $("#password2").val();
        var regdata = {
            username: username,
            password: password
        };
        $.ajax({
            url:"RegisterServlet",
            method: "POST",
            data: regdata,
            success: function (data) {
                //注册成功
            	window.location.href=window.location.href;
            }
        });
    });
});